package com.iris.live.services.services.impl;

import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.common.StringUtils;
import com.iris.live.services.data.repositories.ReportRepository;
import com.iris.live.services.data.repositories.用户Repository;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.report.ExcelReportContext;
import com.iris.live.services.report.IExcelReportService;
import com.iris.live.services.report.IExcelReportSource;
import com.iris.live.services.services.ReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by lusong on 2016/12/9.
 */
@Service
@Transactional
public class ReportServiceImpl implements ReportService {
    private Logger logger = LoggerFactory.getLogger(ReportServiceImpl.class);

    @Autowired
    private IExcelReportService excelReportService;

    @Resource(name = "SaleMonthlyReportSource")
    private IExcelReportSource saleMonthlyReportSource;

    @Resource(name = "LSHROSWeekReportSource")
    private IExcelReportSource LSHROSWeekReportSource;

    @Resource(name = "SmartWeekReportSource")
    private IExcelReportSource SmartWeekReportSource;

    @Resource(name = "SmToBWeekReportSource")
    private IExcelReportSource SmToBWeekReportSource;

    @Resource(name = "FiPerformanceTrackingSource")
    private IExcelReportSource fiPerformanceTrackingSource;


    @Resource(name = "GroupSaleMonthlyReportSource")
    private IExcelReportSource GroupSaleMonthlyReportSource;

    @Resource(name="ExportCluesSource")
    private IExcelReportSource exportCluesSource;

    @Resource(name="ExportFlowLogSource")
    private IExcelReportSource exportFlowLogSource;

    @Autowired
    private ReportRepository reportRepository;

    @Autowired
    private 用户Repository userRepository;

    @Override
    public void getSalesManagerReport(String username, String year, HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/销售管理报表模板.xlsx")
                    .setFileName(year + "年销售管理报表.xlsx")
                    .setSource(saleMonthlyReportSource)
                    .setStaticSheet(false)
                    .addParam("username", username).addParam("year", year);

            excelReportService.export(context, response);
        } catch (Exception exc) {
            logger.error("报表[销售管理报表]导出异常。", exc);
        }
    }


    @Override
    public void getManagerWeekReport(String username, HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/周报表.xlsx")
                    .setFileName("LSH SM2a ROS Weekly Report_Week.xlsx")
                    .setSource(LSHROSWeekReportSource)
                    .setStaticSheet(false)
                    //.setClonableSheet(2)  读取第三个  sheet（不写默认为第一个sheet）
                    .addParam("username", username);

            excelReportService.export(context, response);
        } catch (Exception exc) {
            logger.error("报表[LSH SM2a ROS Weekly Report_Week]导出异常。", exc);
        }
    }

    @Override
    public void getLSHWeekReportOneShop(String permit, HttpServletResponse response,String date) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/周报表.xlsx")
                    .setFileName("LSH SM2a ROS Weekly Report_Week.xlsx")
                    .setSource(LSHROSWeekReportSource)
                    .setStaticSheet(false)
                    //.setClonableSheet(2)  读取第三个  sheet（不写默认为第一个sheet）
                    .addParam("permit", permit).addParam("date", date);
            excelReportService.export(context, response);
        } catch (Exception exc) {
            logger.error("报表[LSH SM2a ROS Weekly Report_Week]导出异常。", exc);
        }
    }

    @Override
    public void getSmartWeekReportSourceOneShop(String permit, HttpServletResponse response,String date) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/smart周报表.xlsx")
                    .setFileName("Smart SM2a ROS Weekly Report_Week.xlsx")
                    .setSource(SmartWeekReportSource)
                    .setStaticSheet(false)
                    //.setClonableSheet(2)  读取第三个  sheet（不写默认为第一个sheet）
                    .addParam("permit", permit).addParam("date", date);
            excelReportService.export(context, response);
        } catch (Exception exc) {
            logger.error("报表[Smart SM2a ROS Weekly Report_Week]导出异常。", exc);
        }
    }

    @Override
    public void getSmToBWeekReportSourceOneShop(String permit, HttpServletResponse response, String date) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/SM2b Purchase Report.xlsx")
                    .setFileName("SM2b Purchase Report.xlsx")
                    .setSource(SmToBWeekReportSource)
                    .setStaticSheet(false)
                    //.setClonableSheet(2)  读取第三个  sheet（不写默认为第一个sheet）
                    .addParam("permit", permit)
                    .addParam("date", date);
            excelReportService.export(context, response);
        } catch (Exception exc) {
            logger.error("报表[SM2b Purchase Report]导出异常。", exc);
        }
    }

    @Override
    public void getFIPerformanceTrackingRpt(String permit, String year, HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/FI月报表.xlsx")
                    .setFileName("FIReport.xlsx")
                    .setSource(fiPerformanceTrackingSource)
                    .setStaticSheet(false)
                    //.setClonableSheet(2)  读取第三个  sheet（不写默认为第一个sheet）
                    .addParam("permit", permit).addParam("year", year);
            excelReportService.export(context, response);
        } catch (Exception e) {
            logger.error("报表[F&I Performance Tracking Report]导出异常。", e);
        }
    }

    @Override
    public void getSalesManagerReportAboutE2(String username, String year, HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/E2销售管理报表.xls")
                    .setFileName("E2销售管理报表.xls")
                    .setSource(GroupSaleMonthlyReportSource)
                    .setStaticSheet(true)
                    .addParam("username", username).addParam("year", year);

            excelReportService.export(context, response);
        } catch (Exception exc) {
            logger.error("报表[销售管理报表]导出异常。", exc);
        }
    }

    @Override
    public void exportCluesList(String isPage ,String dealer, String startTime,String endTime,HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            if("1".equals(isPage)){ context.setTemplate("templates/跟进线索清单报告模板.xlsx");}

            else{ context.setTemplate("templates/跟进线索清单报告模板sum.xlsx");}

            context.setFileName("经销商 跟进线索清单报告模板.xlsx")
                    .setSource(exportCluesSource)
                    .setStaticSheet(false)
                    .setStartCellIndex(0)
                    .setEndCellIndex(18)
                    .setAutoRowExtended(true)
                    .addParam("dealer", dealer)//许可，经销商
                    //.addParam("columns", columns)//列名（[列明，num],...）
                    .addParam("startTime",startTime)
                    .addParam("endTime", endTime)
                    .addParam("isPage",isPage);

            excelReportService.export(context, response);
        } catch (Exception e) {
            logger.error("导出线索信息异常", e);
        }
    }

    @Override
    public void exportFlowLogList(String isPage,String isClue,String dealer, String startTime, String endTime, HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            if("1".equals(isClue)){
                context.setTemplate("templates/FrontdeskReceptionClueBenzLog.xlsx");
            }
            else if("1".equals(isPage)){
                context.setTemplate("templates/FrontdeskReceptionBenzLog.xlsx");
            }
            else{
                context.setTemplate("templates/FrontdeskReceptionBenzLogSum.xlsx");
            }
            context  .setFileName("展厅客流日志.xlsx")
                    .setSource(exportFlowLogSource)
                    .setStaticSheet(false)
                    .setStartCellIndex(0)
                    .setEndCellIndex(18)
                    .setAutoRowExtended(true)
                    .addParam("dealer", dealer)//许可，经销商
                    //.addParam("columns", columns)//列名（[列明，num],...）
                    .addParam("startTime",startTime)
                    .addParam("endTime", endTime)
                    .addParam("isPage",isPage)
                    .addParam("isClue",isClue);
            excelReportService.export(context, response);
        } catch (Exception e) {
            logger.error("导出线索信息异常", e);
        }
    }


    @Override
    public ResultData findFlowInfo (Map map) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (map != null) {
            String message = "", dealer = null, startTime = null, endTime = null, carType = null, isToday = null, scCode = null;
            if (StringUtils.isNullOrBlank(map.get("dealer"))) {
                message = "经销商许可不能为空;";
                logger.error("查询展厅客流日志，经销商许可为空");
            } else {
                dealer = map.get("dealer").toString();
            }
            if (!StringUtils.isNullOrBlank(map.get("startTime"))) {
                startTime = map.get("startTime").toString();
            }
            if (!StringUtils.isNullOrBlank(map.get("endTime"))) {
                endTime = map.get("endTime").toString();
            }
            //现版本车型不作为筛选条件，以后会用到 --路松 2017-09-11
            if (!StringUtils.isNullOrBlank(map.get("carType"))
                    && !"all".equalsIgnoreCase(map.get("carType").toString())
                    && !"全部".equalsIgnoreCase(map.get("carType").toString())) {
                carType = map.get("carType").toString();
            }
            if (!StringUtils.isNullOrBlank(map.get("isToday"))) {
                isToday = map.get("isToday").toString();
            }
            if (!StringUtils.isNullOrBlank(map.get("saleconsultant"))
                    && !"all".equalsIgnoreCase(map.get("saleconsultant").toString())
                    && !"全部".equalsIgnoreCase(map.get("saleconsultant").toString())) {
                scCode = map.get("saleconsultant").toString();
            }
            if (!"Y".equals(isToday)  && (StringUtils.isNullOrBlank(startTime) || StringUtils.isNullOrBlank(endTime))) {
                message = message + "请选择导出展厅客流日志的时段";
                logger.error("查询展厅客流日志--未选择查询时段时段");
            }
            //如果选择 导出当天的客流日志，那么给startTime, endTime赋值 默认当天
            if (!StringUtils.isNullOrBlank(isToday) && "Y".equals(isToday)) {
                startTime = DateFormatUtils.getFormatDateToString(new Date(), "yyyy-MM-dd");
                endTime = startTime;
            }
            //message 为空，调用方法查询客流日志,不为空，返回
            if (StringUtils.isNullOrBlank(message)) {
                int pageSize = 0, pageIndex = 0;
                if(StringUtils.isNotNullOrBlank(map.get("pageNum"))){
                    pageSize = 30;
                    pageIndex = Integer.valueOf(map.get("pageNum").toString()) - 1;
                }

                PageData pd  = reportRepository.getDisplayFlowInfo(dealer, carType, startTime, endTime, scCode, pageSize, pageIndex);
                if(pageSize != 0) {
                    if (pd.getTotal() % pageSize == 0) {
                        pd.setTotal(pd.getTotal() / pageSize);
                    } else {
                        pd.setTotal(pd.getTotal() / pageSize + 1);
                    }
                }
                resultData.setResult("true");
                resultData.setPageData(pd);
            } else {
                resultData.setMessage(message);
            }
        }
        return resultData;
    }

    @Override
    public Map flowClueNum(Map params) throws Exception {
        String dealer = null;
        if (params != null) {
            if (!StringUtils.isNullOrBlank(params.get("isToday")) && "Y".equals(params.get("isToday"))) {
                if (!StringUtils.isNullOrBlank(params.get("dealer"))) {
                    dealer = params.get("dealer").toString();
                } else {
                    logger.error("展厅客流日志查询线索数--经销商许可为空");
                }
            } else {
                logger.info("展厅客流日志查询线索数--查询的不是当天展厅流量日志");
            }
        }
        if (StringUtils.isNullOrBlank(dealer)) {
            return null;
        }
        return reportRepository.getClueInfo(dealer);
    }

    @Override
    public List getShowFlowupReport(String username,String dealer, String startTime,String endTime,HttpServletResponse response) {
        List<Map<String,Object>> list=new ArrayList<>();
        List<Map<String,Object>> listLast=new ArrayList<>();
        if (StringUtils.isNullOrBlank(dealer)){
            dealer=userRepository.findPermitByUsername(username);
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if(endTime.equals(sdf.format(new Date()))){//含当天时间
                //if(endTime.equals("2017-03-08")){//含当天时间
                list = reportRepository.getCurrentCluesList(dealer,endTime);//当天数据
                if(startTime.equals(endTime)){  //只查当天数据

                }else{//查含有今天的区间范围
                    listLast = reportRepository.getCluesListDate(dealer,startTime,endTime);
                    list.addAll(listLast);
                }
            }else {//不含当天时间
                list = reportRepository.getCluesListDate(dealer, startTime, endTime);
            }
            if(list != null) {
                for (Object o : list) {
                    Map map = (Map) o;
                    String phone = (String) map.get("电话号码");
                    if (11 == phone.length()) {
                        phone = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
                        map.put("电话号码", phone);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("跟进线索查看", e);
        }
        return list;
    }
}
